<template>
  <q-card
    style="height: 100%;"
  >
    <q-card-section style="height:  calc(100% - 50px)">
      <v-chart class="chart" :option="option" autoresize />
      <q-btn
        unelevated
        size="sm"
        style="position: absolute; top: 100px; right: 18px;"
        icon-right="system_update_alt"
        :label="csvOver?'Download csv':''"
        :color="csvOver?'primary':'grey-10'"
        text-color=""
        no-caps
        flat
        dense
        @mouseover="csvOver = true"
        @mouseleave="csvOver = false"
        @click="genDefaultCSV()"
      />
    </q-card-section>
  </q-card>
</template>

<script setup lang="ts">
import VChart, { THEME_KEY } from 'vue-echarts';
import * as echarts from 'echarts';
import { use } from 'echarts/core';
import { SVGRenderer, CanvasRenderer } from 'echarts/renderers';
import {
  PieChart,
  LineChart,
  BarChart,
  SunburstChart,
  MapChart,
} from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  // SingleAxisComponent,
  ToolboxComponent,
  AxisPointerComponent,
  VisualMapComponent,
  GeoComponent,
} from 'echarts/components';
import { useInputOption } from 'src/stores/inputOptionStore';
import { ref, provide, computed, onMounted, reactive } from 'vue';
import { OutgoingRecord } from 'src/services/type';
import { formatDateTimeString } from 'src/utils/dateUtils';
import { getOverhaulIndex, getSpareAvailability } from 'src/services/reportService'
import { exportTable } from 'src/utils/exportCsvUtils';

const props = withDefaults(
  defineProps<{
    mode: 'report' | 'dashboard';
  }>(),
  {
    mode: 'report',
  }
);

const csvOver = ref(false)

const inputOptionStore = useInputOption();
const curMonth = new Date().getMonth() + 1;


inputOptionStore.initYears(2018);

const rows = ref<OutgoingRecord[]>([]);
const latest =
  inputOptionStore.yearOptions[inputOptionStore.yearOptions.length - 1];
const year = ref(latest);

const month = ref(curMonth.toString());
const monthOptions = [
  '01',
  '02',
  '03',
  '04',
  '05',
  '06',
  '07',
  '08',
  '09',
  '10',
  '11',
  '12',
];

const filterRows = computed(() => {
  return rows.value;
});
const posList = [
  'left',
  'right',
  'top',
  'bottom',
  'inside',
  'insideTop',
  'insideLeft',
  'insideRight',
  'insideBottom',
  'insideTopLeft',
  'insideTopRight',
  'insideBottomLeft',
  'insideBottomRight',
] as const;


let app: any = {};
app.config = {
  rotate: 90,
  align: 'left',
  verticalAlign: 'middle',
  position: 'insideBottom',
  distance: 15,
  onChange: function () {
    const labelOption: BarLabelOption = {
      rotate: app.config.rotate as BarLabelOption['rotate'],
      align: app.config.align as BarLabelOption['align'],
      verticalAlign: app.config
        .verticalAlign as BarLabelOption['verticalAlign'],
      position: app.config.position as BarLabelOption['position'],
      distance: app.config.distance as BarLabelOption['distance'],
    };
    myChart.setOption<echarts.EChartsOption>({
      series: [
        {
          label: labelOption,
        },
        {
          label: labelOption,
        },
        {
          label: labelOption,
        },
        {
          label: labelOption,
        },
      ],
    });
  },
};

type BarLabelOption = NonNullable<echarts.BarSeriesOption['label']>;


const labelOption: BarLabelOption = {
  show: true,
  position: app.config.position as BarLabelOption['position'],
  distance: app.config.distance as BarLabelOption['distance'],
  align: app.config.align as BarLabelOption['align'],
  verticalAlign: app.config.verticalAlign as BarLabelOption['verticalAlign'],
  rotate: app.config.rotate as BarLabelOption['rotate'],
  formatter: '{c}  {name|{a}}',
  fontSize: 16,
  rich: {
    name: {},
  },
};


const option = reactive({
  title: {
    text: `Overhaul Index (${month.value}-${year.value})`,
    left: 'center',
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#999'
      }
    }
  },
  toolbox: {
    show: true,
    orient: 'vertical',
    right: 0,
    top: 120,
    feature: {
      mark: { show: true },
      dataView: { show: false, readOnly: false },
      magicType: { show: false, type: ['line', 'bar', 'stack'] },
      restore: { show: false },
      saveAsImage: { show: true },
    },
  },
  legend: {
    data: ['Monthly Index', '3 months moving average'],
    orient: 'horizontal',
    right: 0,
    bottom: 0,
  },
  xAxis: [
    {
      type: 'category',
      axisTick: { show: false },
      data: [] as string[],
      axisPointer: {
        type: 'shadow'
      },
      axisLabel: {
        interval: 0,
        rotate: 30, //If the label names are too long you can manage this by rotating the label.
      },
    }
  ],
  yAxis: [
    {
      type: 'value',
      name: 'Monthly Index',
      min: 0,
      max: 100,
      interval: 20,
      axisLabel: {
        formatter: '{value} %'
      }
    },
    {
      type: 'value',
      name: '3 months moving average',
      min: 0,
      max: 100,
      interval: 20,
      axisLabel: {
        formatter: '{value} %'
      }
    }
  ],
  grid: { containLabel: true },
  series: [
  ]
});
async function genDefaultCSV(){
  const row = rows.value[0]
  console.log(row);
  const cols = []
  for(const col in row){
    cols.push( {
    name: col,
    label: col,
    field: col,
    sortable: true,
    search: true,
    align,
  },)
  }
  const output = rows.value
  exportTable(cols,output,'Overhaul Index')
}


async function initData() {
  const res = await getOverhaulIndex(year.value,month.value);
  console.log(res);
  
  
  rows.value = res.data;
  option.xAxis[0].data = res.category

  for (const key in res) {
    if (key=='category') continue
    if (key=='overhaul_index'){
      option.series.push({
        name: 'Monthly Index',
        type: 'bar',
        tooltip: {
          valueFormatter: function (value) {
            return value + ' %';
          }
        },
        data: res[key]
      })
    }
    if (key=='3_month_average'){
      option.series.push({
      name: '3 months moving average',
      type: 'line',
      yAxisIndex: 1,
      tooltip: {
        valueFormatter: function (value) {
          return value + ' %';
        }
      },
      data: res[key]
    })
    }
     
  }
}
initData()

use([
  SVGRenderer,
  CanvasRenderer,
  PieChart,
  BarChart,
  LineChart,
  MapChart,
  SunburstChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  ToolboxComponent,
  AxisPointerComponent,
  VisualMapComponent,
  GeoComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  PieChart,
  CanvasRenderer,
]);

provide(THEME_KEY, 'light');

// const props = withDefaults(defineProps<{
//   mode: 'dashboard' | 'report'
// }>(),{
//   mode: 'report'
// })

const align = 'left';

const columns = [
  {
    name: 'id',
    label: '#',
    field: 'id',
    sortable: true,
    align,
    style: 'width: 10px',
    headerStyle: 'width: 10px',
  },
  {
    name: 'stock_code',
    label: 'Stock Code',
    field: 'stock_code',
    sortable: true,
    align,
  },
  {
    name: 'serial_no',
    label: 'Serial No',
    field: 'serial_no',
    sortable: true,
    align,
  },
  {
    name: 'system',
    label: 'System',
    field: 'system',
    sortable: true,
    align,
  },
  {
    name: 'description',
    label: 'Short Description',
    field: 'description',
    sortable: true,
    align,
  },
  {
    name: 'sw_ver',
    label: 'S/W Version',
    field: 'sw_ver',
    sortable: true,
    align,
  },

  {
    name: 'check_in',
    label: 'Check In',
    field: 'check_in',
    format: (v) => formatDateTimeString(v),
    sortable: true,
    align,
  },
  {
    name: 'check_out',
    label: 'Check Out',
    field: 'check_out',
    format: (v) => formatDateTimeString(v),
    sortable: true,
    align,
  },
  {
    name: 'duration',
    label: 'Duration',
    field: 'duration',
    sortable: true,
    align,
  },
  {
    name: 'category',
    label: 'Category',
    field: 'category',
    sortable: true,
    align,
  },
];
</script>

<style scoped></style>
